<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ 'collapsed': isCollapsed }">
      <!-- 品牌Logo区域 -->
      <div class="sidebar-header">
        <div class="logo-container">
          <div class="logo-icon">
            <i class="el-icon-coffee"></i>
          </div>
          <h1 v-if="!isCollapsed" class="logo-text">云咖管理系统</h1>
        </div>
        <button class="toggle-btn" @click="toggleCollapse" :title="isCollapsed ? '展开菜单' : '收起菜单'">
          <i :class="isCollapsed ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
        </button>
      </div>

      <!-- 菜单区域 -->
      <nav class="menu-container">
        <ul class="menu-list">
          <template v-for="menu in adminMenus">
            <li
              v-if="!menu.meta || !menu.meta.hidden"
              class="menu-item"
              :key="menu.name"
            >
              <!-- 有子菜单的父项 -->
              <div
                v-if="hasChildren(menu)"
                class="parent-menu"
                @click="toggleSubmenu(menu)"
                :class="{ 'active': menu.isOpen }"
              >
                <i :class="menu.meta?.icon || 'el-icon-menu'" class="menu-icon"></i>
                <span v-if="!isCollapsed" class="menu-text">{{ menu.meta?.title || '未命名菜单' }}</span>
                <i
                  :class="menu.isOpen ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                  class="menu-arrow"
                  v-if="!isCollapsed"
                ></i>
              </div>

              <!-- 无子菜单的项 -->
              <router-link
                v-else
                :to="getFullPath(menu)"
                class="menu-link"
                :class="{ 'active': isActive(menu) }"
              >
                <i :class="menu.meta?.icon || 'el-icon-document'" class="menu-icon"></i>
                <span v-if="!isCollapsed" class="menu-text">{{ menu.meta?.title || '未命名菜单' }}</span>
              </router-link>

              <!-- 子菜单列表 -->
              <ul
                v-if="hasChildren(menu) && menu.isOpen"
                class="submenu-list"
                :style="{ paddingLeft: isCollapsed ? '0' : '16px' }"
              >
                <li
                  v-for="subMenu in menu.children"
                  :key="subMenu.name"
                  v-if="!subMenu.meta || !subMenu.meta.hidden"
                >
                  <router-link
                    :to="getFullPath(subMenu)"
                    class="submenu-link"
                    :class="{ 'active': isActive(subMenu) }"
                  >
                    <span v-if="!isCollapsed">{{ subMenu.meta?.title || '未命名子菜单' }}</span>
                    <span v-if="isCollapsed" class="collapsed-tooltip">{{ subMenu.meta?.title || '子菜单' }}</span>
                  </router-link>
                </li>
              </ul>
            </li>
          </template>
        </ul>
      </nav>

      <!-- 底部装饰 -->
      <div class="sidebar-footer" v-if="!isCollapsed">
        <div class="footer-info">
          <p class="version">版本: v1.0.0</p>
          <p class="copyright">© 2025 中国云咖后台管理系统</p>
        </div>
      </div>
    </aside>

    <!-- 主内容区 (保持不变) -->
    <main class="main-content">
      <header class="main-header">
        <!-- 头部内容保持不变 -->
        <div class="user-info">
<div class="user-info">
  <!-- 1. 下拉触发按钮（点击显示/隐藏菜单） -->
  <div class="dropdown-trigger" @click="toggleDropdown">
    <span>{{ $store.state.profile?.username || '管理员' }}</span>
    <i class="el-icon-arrow-down" :class="{ 'rotate': isDropdownOpen }"></i> <!-- 箭头旋转动画 -->
  </div>

  <!-- 2. 下拉菜单（默认隐藏，点击触发按钮显示） -->
  <div class="dropdown-menu" v-if="isDropdownOpen">
    <ul>
      <!-- 个人中心（点击触发 tiaozhuan 方法） -->
      <li @click="() => { tiaozhuan(); toggleDropdown(); }">
        <i class="el-icon-user"></i> 个人中心
      </li>
      <!-- 退出登录（点击触发 handleLogout 方法） -->
      <li @click="() => { handleLogout(); toggleDropdown(); }">
        <i class="el-icon-switch-button"></i> 退出登录
      </li>
    </ul>
  </div>
</div>
        </div>
      </header>

      <div class="page-content">
        <router-view />
      </div>
    </main>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isCollapsed: false,
      adminMenus: [],
      isDropdownOpen: false
    }
  },

  created() {
    this.initAdminMenus()
     console.log('路由实例：', this.$router)
  },

  methods: {
     toggleDropdown() {
    this.isDropdownOpen = !this.isDropdownOpen;
  },
     tiaozhuan() {
    console.log('触发个人中心跳转，目标路径：/admin/user-center');
    this.$router.push('/admin/user-center')
      .then(() => {
        console.log('跳转成功！当前路径：', this.$route.path);
      })
      .catch(error => {
        console.error('跳转失败原因：', error);
        this.$message.error('跳转失败，请检查路由配置');
      });
  },
    initAdminMenus() {
      try {
        const adminRoute = this.$router.options.routes.find(route => route.name === 'AdminLayout')
        if (adminRoute && adminRoute.children) {
          this.adminMenus = JSON.parse(JSON.stringify(adminRoute.children))

          this.adminMenus.forEach(menu => {
            if (!menu.meta) menu.meta = {}
            menu.isOpen = this.hasActiveChild(menu)
          })
        }
      } catch (error) {
        console.error('初始化菜单失败:', error)
        this.adminMenus = []
      }
    },

    hasChildren(menu) {
      return menu.children && menu.children.length > 0
    },

    toggleSubmenu(menu) {
      if (this.hasChildren(menu)) {
        this.$set(menu, 'isOpen', !menu.isOpen)
      }
    },

    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed
    },

    getFullPath(menu) {
      return `/admin/${menu.path}`.replace('//', '/')
    },

    isActive(menu) {
      const fullPath = this.getFullPath(menu)
      return this.$route.path.startsWith(fullPath)
    },

    hasActiveChild(menu) {
      if (!this.hasChildren(menu)) return false

      return menu.children.some(subMenu => {
        if (this.isActive(subMenu)) return true
        return this.hasActiveChild(subMenu)
      })
    },

    async handleLogout() {
      try {
        await this.$confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        localStorage.removeItem('token')
        this.$store.commit('CLEAR_PROFILE')
        this.$router.replace('/login')
        this.$message.success('退出登录成功')
      } catch (_) {
        this.$message.info('已取消退出登录')
      }
    }
  },

  watch: {
    $route() {
      this.adminMenus.forEach(menu => {
        menu.isOpen = this.hasActiveChild(menu)
      })
    }
  }
}
</script>

<style scoped>
/* 基础布局 */
.admin-layout {
  display: flex;
  min-height: 100vh;
}

/* 侧边栏主体 */
.sidebar {
  width: 250px;
  background-color: #3D2314; /* 深咖啡色 */
  color: #F5E8C8; /* 米黄色文字 */
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  height: 100vh;
  position: fixed;
  overflow-y: auto;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

/* 侧边栏折叠状态 */
.sidebar.collapsed {
  width: 70px;
}

/* 侧边栏头部 */
.sidebar-header {
  padding: 18px 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo-container {
  display: flex;
  align-items: center;
}

.logo-icon {
  width: 40px;
  height: 40px;
  background-color: #D4A76A; /* 铜色图标背景 */
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.logo-icon i {
  font-size: 20px;
  color: #3D2314; /* 图标颜色与深咖啡匹配 */
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  letter-spacing: 0.5px;
}

/* 折叠按钮 */
.toggle-btn {
  background: transparent;
  border: none;
  color: #F5E8C8;
  cursor: pointer;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.toggle-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 菜单容器 */
.menu-container {
  padding-top: 15px;
}

.menu-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu-item {
  margin-bottom: 4px;
}

/* 父菜单样式 */
.parent-menu {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s;
  border-left: 3px solid transparent;
}

.parent-menu:hover {
  background-color: #4A2C1A; /* 稍浅的咖啡色 */
}

.parent-menu.active {
  background-color: #4A2C1A;
  border-left-color: #D4A76A; /* 铜色高亮边框 */
}

/* 菜单链接样式 */
.menu-link {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: #F5E8C8;
  text-decoration: none;
  transition: all 0.2s;
  border-left: 3px solid transparent;
}

.menu-link:hover {
  background-color: #4A2C1A;
}

.menu-link.active {
  background-color: #4A2C1A;
  border-left-color: #D4A76A;
}

/* 菜单图标和文字 */
.menu-icon {
  font-size: 18px;
  width: 24px;
  text-align: center;
}

.menu-text {
  margin-left: 12px;
  font-size: 14px;
}

.menu-arrow {
  font-size: 14px;
  transition: transform 0.2s;
}

/* 子菜单样式 */
.submenu-list {
  list-style: none;
  margin: 0;
  padding: 0;
  background-color: #432818; /* 比父菜单更深一点的颜色 */
  transition: all 0.3s;
}

.submenu-link {
  display: block;
  padding: 10px 20px 10px 40px;
  color: #E6D5B8; /* 稍浅的文字色 */
  text-decoration: none;
  font-size: 13px;
  transition: all 0.2s;
}

.submenu-link:hover {
  background-color: #4A2C1A;
  color: #F5E8C8;
  padding-left: 42px;
}

.submenu-link.active {
  background-color: #4A2C1A;
  color: #D4A76A; /* 铜色高亮 */
  font-weight: 500;
}

/* 折叠状态下的提示 */
.collapsed-tooltip {
  position: relative;
}

.collapsed-tooltip::after {
  content: attr(data-title);
  position: absolute;
  left: 70px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #3D2314;
  color: #F5E8C8;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.collapsed-tooltip:hover::after {
  opacity: 1;
  visibility: visible;
}

/* 侧边栏底部 */
.sidebar-footer {
  padding: 20px 15px;
  margin-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.footer-info .version {
  font-size: 12px;
  color: #C8B6A6;
  margin: 0 0 5px 0;
}

.footer-info .copyright {
  font-size: 11px;
  color: #A08A75;
  margin: 0;
}

/* 主内容区样式 (保持与之前一致) */
.main-content {
  flex: 1;
  margin-left: 250px;
  transition: margin-left 0.3s;
  background-color: #f9f7f5;
}

.sidebar.collapsed ~ .main-content {
  margin-left: 70px;
}

.main-header {
  height: 60px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 20px;
  position: fixed;
  top: 0;
  right: 0;
  left: 250px;
  transition: left 0.3s;
  z-index: 5;
}

.sidebar.collapsed ~ .main-content .main-header {
  left: 70px;
}

.page-content {
  padding: 20px;
  margin-top: 60px;
}
  /* 原生下拉菜单样式 - 确保显示正常且点击区域可交互 */
.user-info {
  position: relative; /* 关键：作为下拉菜单的定位容器 */
  cursor: pointer;
  padding: 0 10px;
}

/* 下拉触发按钮样式 */
.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #333;
}

/* 箭头旋转动画 */
.el-icon-arrow-down.rotate {
  transform: rotate(180deg);
  transition: transform 0.2s;
}

/* 下拉菜单样式（默认隐藏，绝对定位） */
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  min-width: 160px;
  background-color: #fff;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 9999; /* 最高层级，避免被遮挡 */
  margin-top: 5px;
}

/* 下拉菜单项样式 */
.dropdown-menu ul {
  list-style: none;
  margin: 0;
  padding: 5px 0;
}

.dropdown-menu li {
  padding: 10px 15px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  cursor: pointer;
}

/* 菜单项 hover 效果 */
.dropdown-menu li:hover {
  background-color: #f5f5f5;
  color: #3D2314; /* 咖啡色系，和整体风格统一 */
}

/* 菜单项图标样式 */
.dropdown-menu li i {
  color: #8B5A2B;
}
</style>
